package ntd.remote.file.impl;

import cn.hutool.json.JSONUtil;
import lj.a.protocol.lj.bean.LJProtocolInfo;
import lj.netty.bean.LJNettyMsgContext;
import ntd.remote.file.ComRemoteFile;
import ntd.remote.file.action.ActionRemoteAdd;
import ntd.remote.file.action.ActionRemoteDel;
import ntd.remote.file.action.ActionRemoteList;
import ntd.remote.file.action.ActionRemoteRead;
import ntd.remote.file.bo.ComRemoteFileBO;
import ntd.remote.link.ComRegistryClient;
import ntd.remote.link.bo.MsgBO;

import java.util.List;

/**
 * 远程文件功能实现
 */
public class ComRemoteFileImpl implements ComRemoteFile {

    @Override
    public void move(ComRemoteFileBO sourceFileBO, ComRemoteFileBO targetFileBO) {
        add(targetFileBO, readFile(sourceFileBO));
        del(sourceFileBO);
    }

    @Override
    public void copy(ComRemoteFileBO sourceFileBO, ComRemoteFileBO targetFileBO) {
        add(targetFileBO, readFile(sourceFileBO));
    }

    @Override
    public void del(ComRemoteFileBO targetFileBO) {
        MsgBO msgBo = new MsgBO().setData(JSONUtil.toJsonStr(targetFileBO)).setActionCode(ActionRemoteDel.ACTION_CODE);
        ComRegistryClient.ljNettyListen.pushMsgAll(new LJProtocolInfo().setGoalTerminal(
            targetFileBO.getRemoteCode()).setData(JSONUtil.toJsonStr(msgBo).getBytes()));
    }

    @Override
    public void add(ComRemoteFileBO targetFileBO, byte[] bytes) {
        MsgBO msgBo = new MsgBO().setData(JSONUtil.toJsonStr(targetFileBO)).setActionCode(ActionRemoteAdd.ACTION_CODE);
        ComRegistryClient.ljNettyListen.pushMsgAll(new LJProtocolInfo().setGoalTerminal(
                targetFileBO.getRemoteCode()).setData(JSONUtil.toJsonStr(msgBo).getBytes()).setBytes(bytes));
    }

    @Override
    public byte[] readFile(ComRemoteFileBO targetFileBO) {
        MsgBO msgBo = new MsgBO().setData(JSONUtil.toJsonStr(targetFileBO)).setActionCode(ActionRemoteRead.ACTION_CODE);
        LJNettyMsgContext ljNettyMsgContext = ComRegistryClient.ljNettyListen.pushMsgAll(new LJProtocolInfo().setGoalTerminal(
                targetFileBO.getRemoteCode()).setData(JSONUtil.toJsonStr(msgBo).getBytes()));
        return ljNettyMsgContext.getLjProtocolInfo().getBytes();
    }

    @Override
    public List<ComRemoteFileBO> loopListFiles(ComRemoteFileBO targetFileBO) {
        MsgBO msgBo = new MsgBO().setData(JSONUtil.toJsonStr(targetFileBO)).setActionCode(ActionRemoteList.ACTION_CODE);
        LJNettyMsgContext ljNettyMsgContext = ComRegistryClient.ljNettyListen.pushMsgAll(new LJProtocolInfo().setGoalTerminal(
                targetFileBO.getRemoteCode()).setData(JSONUtil.toJsonStr(msgBo).getBytes()));
        return JSONUtil.toList(new String(ljNettyMsgContext.getLjProtocolInfo().getBytes()), ComRemoteFileBO.class);
    }
}
